//
//  XQCustomOptionalPop.m
//  JoinPeso
//
//  Created by 小琦 on 2024/11/24.
//

#import "XQCustomOptionalPop.h"
#import "XQCustomOptionCell.h"

@interface XQCustomOptionalPop()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UIView *centerView;
@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) UILabel *titleLb;
@property (nonatomic,strong) UIButton *closeButton;
@property (nonatomic,strong) UIButton *confimButton;
@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) UIView *middleView;

@property (nonatomic,copy) NSString *title;
@property (nonatomic,copy) NSArray *datas;

@property (nonatomic, assign) NSInteger selectRow;

@end

@implementation XQCustomOptionalPop

- (instancetype)initWithTitle:(NSString *)title datas:(NSArray *)datas {
    self = [super init];
    if (self) {
        _title = title;
        _datas = datas;
        [self makeUI];
        [self makeConstraints];
    }
    return self;
}

- (void)makeUI {
    [self addSubview:self.centerView];
    [self.centerView addSubview:self.imageView];
    [self.imageView addSubview:self.titleLb];
    [self.imageView addSubview:self.closeButton];
    [self.centerView addSubview:self.confimButton];
    [self.imageView addSubview:self.middleView];
    [self.imageView addSubview:self.tableView];
    
}

- (void)makeConstraints {
    [self.centerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        (void)make.center;
    }];
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.equalTo(@12);
        make.right.equalTo(@-12);
        make.height.mas_equalTo(213);
    }];
    [self.confimButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.imageView.mas_bottom).offset(10);
        make.left.equalTo(@12);
        make.right.equalTo(@-12);
        make.width.mas_equalTo([UIScreen mainScreen].width - 24);
        make.height.mas_equalTo(45);
        make.bottom.equalTo(@0);
    }];
    [self.titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        (void)make.centerX;
        make.top.equalTo(@12);
    }];
    [self.closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@12);
        make.right.equalTo(@-10);
        make.height.width.mas_equalTo(22);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@62.5);
        make.left.equalTo(@10);
        make.right.equalTo(@-10);
        make.bottom.equalTo(@-30);
    }];
    [self.middleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@110);
        make.height.mas_equalTo(30);
        make.left.equalTo(@20);
        make.right.equalTo(@-20);
    }];
}

#pragma mark - setter

- (void)setTitle:(NSString *)title {
    self.titleLb.text = title;
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count + 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XQCustomOptionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XQCustomOptionCell" forIndexPath:indexPath];
    if (indexPath.row == 0 || indexPath.row == self.datas.count + 1) {
        [cell setContent:@""];
    }else {
        NSString *con = self.datas[indexPath.row - 1];
        [cell setContent:con];
    }
    [cell setIsSelected:self.selectRow == indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0 || indexPath.row == self.datas.count + 1) return;
    self.selectRow = indexPath.row;
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    [self.tableView reloadData];
}

#pragma mark - setter

- (void)setSelctData:(NSString *)selctData {
    _selctData = selctData;
    int index = 1;
    for (int i = 0; i < self.datas.count; i++) {
        if ([[self.datas[i] lowercaseString] isEqualToString:[selctData lowercaseString]]) {
            index = i;
            break;
        }
    }
    self.selectRow = index + 1;
    
    if (selctData.length) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.selectRow < 0) {
                return;
            }
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.selectRow inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
        });
    }
}

#pragma mark - private

- (void)confimClick {
    if (self.confimHandle) {
        self.confimHandle(self.datas[self.selectRow - 1]);
    }
    
    if (self.confimIndexHandle) {
        self.confimIndexHandle(self.selectRow - 1);
    }
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.selectRow = -1;
    [self.tableView reloadData];
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    CGFloat rowHeight = 40; // 每行的高度
    CGFloat targetY = targetContentOffset->y;

    // 计算目标行
    NSInteger targetRow = (NSInteger)(targetY / rowHeight + (velocity.y > 0 ? 0.5 : -0.5));
    targetRow = MAX(0, MIN(targetRow, self.datas.count - 1)); // 确保在有效范围内

    self.selectRow = targetRow + 1;
    
    targetContentOffset->y = targetRow * rowHeight;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self.tableView reloadData];
}


#pragma mark - lazy

- (UIView *)centerView {
    if (!_centerView) {
        _centerView = [[UIView alloc] init];
    }
    return _centerView;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
        _imageView.image = [UIImage imageNamed:@"custom_optional_pop"];
        [_imageView setUserInteractionEnabled:YES];
    }
    return _imageView;
}

- (UIButton *)confimButton {
    if (!_confimButton) {
        _confimButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confimButton setTitle:@"Confirm" forState:UIControlStateNormal];
        [_confimButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _confimButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        _confimButton.backgroundColor = [UIColor blueColor];
        _confimButton.layer.cornerRadius = 22.5;
        [_confimButton addTarget:self action:@selector(confimClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confimButton;
}

- (UILabel *)titleLb {
    if (!_titleLb) {
        _titleLb = [[UILabel alloc] init];
        _titleLb.text = self.title;
        _titleLb.textColor = [UIColor whiteColor];
        _titleLb.font = [UIFont boldSystemFontOfSize:18];
    }
    return _titleLb;
}

- (UIButton *)closeButton {
    if (!_closeButton) {
        _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeButton setImage:[UIImage imageNamed:@"pop_close"] forState:UIControlStateNormal];
        [_closeButton addTarget:self action:@selector(confimClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeButton;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.pagingEnabled = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        [_tableView registerClass:[XQCustomOptionCell class] forCellReuseIdentifier:@"XQCustomOptionCell"];
    }
    return _tableView;
}

- (UIView *)middleView {
    if (!_middleView) {
        _middleView = [[UIView alloc] init];
        _middleView.layer.cornerRadius = 8;
        _middleView.backgroundColor = kBlueTextColor;
    }
    return _middleView;
}

@end
